import React, {useState} from 'react';
import {Button, Form, Input, InputNumber, Modal} from 'antd';


type Values = {
    name?: string;
    age?: number;
    address?: string;
};

interface UserModalProps {
    open: boolean;
    onCreate: (values: Values) => void;
    onUpdate: (id: number, values: Values) => void;
    close: () => void;
    currentRecord: any;
}


const UserModal: React.FC<UserModalProps> = (props) => {
    const [loading, setLoading] = useState(false);
    const {onCreate, currentRecord, onUpdate} = props;
    const [form] = Form.useForm();

    const handleOk = () => {
        form
            .validateFields()
            .then((values) => {
                if (currentRecord != null) {
                    onUpdate(currentRecord.id, values);
                } else {
                    onCreate(values);

                }
            })
            .catch((info) => {
                console.log('Validate Failed:', info);
            });

    };

    const handleCancel = () => {
        form.resetFields();
        props.close()
    };

    return (
        <Modal
            open={props.open}
            title={currentRecord != null ? currentRecord.name : '新增'}
            onOk={handleOk}
            onCancel={handleCancel}
            footer={[
                <Button key="back" onClick={handleCancel}>
                    返回
                </Button>,
                <Button key="submit" type="primary" loading={loading} onClick={handleOk}>
                    保存
                </Button>,
            ]}
        >
            <Form preserve={false} form={form}>
                <Form.Item<Values>
                    label="姓名"
                    name="name"
                    initialValue={currentRecord ? currentRecord.name : ''}
                    rules={[{
                        required: true,
                        message: 'Please input your username!',
                    }]}
                >
                    <Input/>
                </Form.Item>
                <Form.Item<Values>
                    label="年龄"
                    name="age"
                    initialValue={currentRecord ? currentRecord.age : ''}
                    rules={[{required: true, message: 'Please input your username!'}]}
                >
                    <InputNumber/>
                </Form.Item>
                <Form.Item<Values>
                    label="地址"
                    initialValue={currentRecord ? currentRecord.address : ''}
                    name="address"
                >
                    <Input/>
                </Form.Item>
            </Form>

        </Modal>
    );
};

export default UserModal;
